# IIS 网站创建脚本
# 需要以管理员权限运行

Import-Module WebAdministration

# 配置参数
$siteName = "FileUploadSystem"
$physicalPath = "C:\inetpub\wwwroot\FileUploadSystem"
$port = 8080

Write-Host "开始创建 IIS 网站..." -ForegroundColor Green

# 检查是否以管理员权限运行
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Write-Host "错误：请以管理员权限运行此脚本！" -ForegroundColor Red
    exit 1
}

# 检查物理路径是否存在
if (-not (Test-Path $physicalPath)) {
    Write-Host "创建物理路径: $physicalPath" -ForegroundColor Yellow
    New-Item -ItemType Directory -Path $physicalPath -Force
}

# 检查端口是否被占用
$portInUse = Get-NetTCPConnection -LocalPort $port -ErrorAction SilentlyContinue
if ($portInUse) {
    Write-Host "警告：端口 $port 已被占用，将使用端口 8081" -ForegroundColor Yellow
    $port = 8081
}

# 检查网站是否已存在
$existingSite = Get-Website -Name $siteName -ErrorAction SilentlyContinue
if ($existingSite) {
    Write-Host "网站 $siteName 已存在，正在删除..." -ForegroundColor Yellow
    Remove-Website -Name $siteName
}

# 创建网站
try {
    New-Website -Name $siteName -PhysicalPath $physicalPath -Port $port
    Write-Host "网站 $siteName 创建成功！" -ForegroundColor Green
} catch {
    Write-Host "创建网站失败: $($_.Exception.Message)" -ForegroundColor Red
    exit 1
}

# 设置应用程序池
try {
    Set-ItemProperty "IIS:\Sites\$siteName" -Name applicationPool -Value "DefaultAppPool"
    Write-Host "应用程序池设置成功" -ForegroundColor Green
} catch {
    Write-Host "设置应用程序池失败: $($_.Exception.Message)" -ForegroundColor Red
}

# 启动网站
try {
    Start-Website -Name $siteName
    Write-Host "网站已启动" -ForegroundColor Green
} catch {
    Write-Host "启动网站失败: $($_.Exception.Message)" -ForegroundColor Red
}

# 显示网站信息
$site = Get-Website -Name $siteName
Write-Host "`n网站信息:" -ForegroundColor Cyan
Write-Host "名称: $($site.Name)"
Write-Host "状态: $($site.State)"
Write-Host "端口: $port"
Write-Host "物理路径: $physicalPath"
Write-Host "应用程序池: $($site.ApplicationPool)"

Write-Host "`n部署完成！" -ForegroundColor Green
Write-Host "请将项目文件复制到: $physicalPath" -ForegroundColor Yellow
Write-Host "访问地址: http://localhost:$port" -ForegroundColor Yellow 